var winston = require('winston');

module.exports = function(pool, req, res, next){
	var eventId = req.params.eventId;
	var type = req.query.type;
	var prefix = req.protocol + "://" + req.hostname + "/assets/" + eventId + "/";
	if(type == 'all'){
		var queryString = 'SELECT pr.print_id, ph.filename, pr.copies, pr.timestamp, pr.is_fullfilled FROM print_list pr LEFT JOIN photo_list ph ON pr.photo_id=ph.photo_id where pr.event_id=' + eventId + ' ORDER BY pr.print_id';
		pool.getConnection(function(err, connection){
			if(err){
				winston.error('DB connection error: ' + err);
				res.status(500).send('DB connection error: ' + err);
			}
			connection.query(queryString, function(err, rows){
				if(err){
					winston.error('DB query error: ' + err);
					res.status(500).send('DB query error: ' + err);
				}else{

					rows.forEach(function(row){
						var filename = row.filename;
						row.filename = prefix + filename;
					});
					res.send(rows);

				}
				connection.release();
			});
		});
	}
	else if(type == 'printed'){
		var queryString = 'SELECT pr.print_id, ph.filename, pr.copies, pr.timestamp FROM print_list pr LEFT JOIN photo_list ph ON pr.photo_id=ph.photo_id WHERE pr.event_id=' + eventId + ' AND is_fullfilled=1 ORDER BY pr.print_id';
		pool.getConnection(function(err, connection){
			if(err){
				winston.error('DB connection error: ' + err);
				res.status(500).send('DB connection error: ' + err);
			}
			connection.query(queryString, function(err, rows){
				if(err){
					winston.error('DB query error: ' + err);
					res.status(500).send('DB query error: ' + err);
				}else{

					rows.forEach(function(row){
						var filename = row.filename;
						row.filename = prefix + filename;
					});
					res.send(rows);

				}
				connection.release();
			});
		});
	}
	else if(type == 'unprinted'){
		var queryString = 'SELECT pr.print_id, ph.filename, pr.copies, pr.timestamp FROM print_list pr LEFT JOIN photo_list ph ON pr.photo_id=ph.photo_id WHERE pr.event_id=' + eventId + ' AND is_fullfilled=0 ORDER BY pr.print_id';
		pool.getConnection(function(err, connection){
			if(err){
				winston.error('DB connection error: ' + err);
				res.status(500).send('DB connection error: ' + err);
			}
			connection.query(queryString, function(err, rows){
				if(err){
					winston.error('DB query error: ' + err);
					res.status(500).send('DB query error: ' + err);
				}else{

					rows.forEach(function(row){
						var filename = row.filename;
						row.filename = prefix + filename;
					});
					res.send(rows);

				}
				connection.release();
			});
		});
	}
	else{
		winston.error('ROUT error, parameters not match.');
		res.status(500).send('ROUT error, parameters not match.')
	}
	
}